/**
 * @Auther: ayo
 * @Date: 2018/10/22 11:05
 * @Description: // 返回时间给定时器用的工具类 TODO: 屏幕关闭或程序后台运行时定时器不执行问题待解决
 */
import { Injectable } from '@angular/core';
import * as moment from 'moment';

@Injectable()
export class TimerUtils {

    timer: any;
    createTimer = (id, deadline) => {
        const timer = this;
        const timeDeadline = moment(deadline).diff(moment());
        const _timer = this.timer[id] = {
            deadline: deadline, id: id, timeDeadline: timeDeadline, interval: () => {
                let returnTime = '';
                const time = _timer.timeDeadline / 1000;
                const day = Math.floor(time / (24 * 3600));
                const hour = Math.floor((time - 24 * 3600 * day) / 3600);
                const minute = Math.floor((time - 24 * 3600 * day - hour * 3600) / 60);
                const second = Math.floor((time - 24 * 3600 * day - hour * 3600 - minute * 60));
                // 这里可以做一个格式化的处理,甚至做毫秒级的页面渲染,基于DOM操作,太多个倒计时一起会导致页面性能下降
                _timer.timeDeadline -= 1000;
                if (_timer.timeDeadline < 0) {
                    // 判断是否到期,到期后自动删除定时器
                    timer.deleteTimer(id);
                }
                if (0 !== second) {
                    returnTime = second + '';
                } else {
                    returnTime = '00';
                }
                if (0 !== minute) {
                    returnTime = minute + ':' + returnTime;
                } else {
                    returnTime = '00' + ':' + returnTime;
                }
                if (0 !== hour) {
                    returnTime = hour + ':' + returnTime;
                } else {
                    returnTime = '00' + ':' + returnTime;
                }
                if (0 !== day) {
                    returnTime = day + ' ' + returnTime;
                }
                return returnTime;
            }
        };
        return _timer;
    };

    deleteTimer = (id) => {
        // 清楚定时器的方法,需要定时器的指针作为参数传入clearInterval
        // clearInterval(this.timer[id].interval);
        // 通过delete的方法删除对象中的属性
        delete this.timer[id];
    };

    getTimer = (id) => {
        if (this.timer[id]) {
            return this.timer[id].interval();
        }
    };

    constructor() {
        this.timer = {};
    }
}
